import { store } from "@/store";
import { getToken } from "@/utils/auth";
import { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { useUserStore } from '@/store/modules/user';
import { useUserStoreWithOut } from "@/store/modules/user";
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
import actions from "@/micro/shared/actions";


// 切换路由 清除所有请求
const cancelToken = (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  // 在跳转路由之前，先清除所有的请求
  // clearPending();
  next();
};

// 登录权限校验
const loginPermission = async function (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const userStore = useUserStore();
  const isLogin = userStore.getToken;

  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    actions.updateState({ key: 'router', value: {...to ,system: import.meta.env.VITE_PUBLIC_PATH }});
  }

  console.log('子应用路由登录',isLogin);

  // 登录过并且当前是登录页---跳转首位
  if (isLogin && to.path === "/login") {
    return next("/");
  }

  // 没登录并且当前不是登录页---跳转登录录页
  if (!isLogin && to.path !== "/login") {
    const userStore = useUserStoreWithOut();
    userStore.logout();
    // return next( { name : 'Login'} );
  }
  next();
};

// 路由权限动态添加
export const menuPermisson = async function (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const userStore = useUserStore();
  const token  = userStore.getToken;
  if (token) {
    if (!userStore.menuPermission) {
      await userStore.addRouter();
      // 添加路由完成，但是是属于异步加载，不会立即更新
      next({ ...to, replace: true }); // 如果是next()时，进入到页面时报404.
    } else {
      next();
    }
  } else {
    next();
  }
};

export const hooks = {
  loginPermission,
  menuPermisson,
  // cancelToken,
};
